// pages2/pages/mall/allClassify/index.js
const app = getApp();
import { arrToTwoArr, getDatetime, getElementDs } from '../../../../utils/util';
const $api = require('../../../../request/api').API;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    menuBtnTop: app.globalData.menuBtnTop,
    fixedTop: 0,
    inputValue: '',
    businessId: '',
    startPrice: '',
    thirdClassifyId: '', //三级分类
    beeperId: '',
    btnId: '',
    btnType: '',
    collect: '',
    classifyIds: '',
    classifyList: [],
    combineList: [],
    pageSize: 20, //一页的个数
    pageNo: 1, //第几页
    totalPage: '', //总页数
    listData: [],
    loading: false, //懒加载数据
    loadingData: false, //页面加载，商品切换的时候用到这个
    spec: {
      goodsId: '',
      showSpec: false,
      beeperId: ''
    },
    shopCartPosition: {},
    addAnimation: '',
    showDot: false,
    dotClientX: '',
    dotClientY: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let beeperId = app.globalData['btnList.beeperId'];
    let btnId = app.globalData['btnList.btnId'];
    let btnType = app.globalData['btnList.btnType'];
    let classifyIds = app.globalData['btnList.btnServerClassifyIds'];
    let queryType = app.globalData['btnList.queryType'];
    this.data.spec.beeperId = beeperId;
    if (btnId) {
      this.setData({
        spec: this.data.spec,
        btnId: btnId,
        beeperId: beeperId ? beeperId : '',
        classifyIds: classifyIds,
        btnType: btnType,
        queryType: queryType,
        businessId: options.businessId,
        startPrice: options.startPrice,
        businessVillageIds: options.businessVillageIds || ''
      });
      this.getStyle();
      this.getListData(true);
      this.getAllService();
      if (this.data.beeperId) {
        this.getCombineList();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  getStyle() {
    getElementDs(['.search-wrapper', '#balance>>>.shop-cart-img']).then(res => {
      this.setData({
        fixedTop: res[0].height,
        shopCartPosition: res[1]
      });
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    this.data.listData.forEach(item => {
      item.nums = 0;
      shopCartList.forEach(item2 => {
        if (item.variantId == item2.variantId) {
          item.nums = item2.nums;
        }
        if (item.goodsId == item2.goodsId && !item.variantId) {
          item.nums = item.nums + item2.nums;
        }
      });
    });
    this.setData({
      listData: this.data.listData
    });
  },
  // 返回上一页
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 阻止冒泡
  stopBubble() {},
  //  获取收藏
  myCollect() {
    this.setData({
      collect: this.data.collect ? '' : 1
    });
    this.getListData(true);
  },
  getListData(isFilter = false) {
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    const { businessId, businessVillageIds } = this.data;
    let params = {
      btnId: this.data.btnId,
      beeperId: this.data.beeperId,
      btnType: this.data.btnType,
      classifyIds: this.data.classifyIds,
      businessId,
      collect: this.data.collect,
      queryType: this.data.queryType,
      name: this.data.inputValue,
      thirdClassifyId: this.data.collect ? '' : this.data.thirdClassifyId,
      pageSize: this.data.pageSize,
      pageNo: this.data.pageNo,
      businessVillageIds
    };

    if (isFilter) {
      this.setData({
        loadingData: true
      });
    } else {
      this.setData({
        loading: true
      });
    }

    $api
      .getShopList(params)
      .then(res => {
        let data = res.data.data;
        // 添加一个nums属性，同时判断购物车里面是否存在该商品，如果存在那么就需要把该商品的数量赋值给商品列表对应的该商品
        data.list.forEach(item => {
          item.nums = 0;
          shopCartList.forEach(item2 => {
            if (item.variantId == item2.variantId) {
              item.nums = item2.nums;
            }
            if (item.goodsId == item2.goodsId && !item.variantId) {
              item.nums = item.nums + item2.nums;
            }
          });
        });

        // 判断是否在活动范围内
        this.activeTime(data.list);
        this.setData({
          // 这里需要做判断,如果isFilter为true就是重新获取列表数据,如果是false就是分页获取数据
          listData: isFilter ? data.list : this.data.listData.concat(data.list),
          pageNo: data.pageNum,
          totalPage: data.totalPage
        });
        // 判断是否超时
        this.judgeTimeout();

        if (this.selectComponent('#tabs')) this.selectComponent('#tabs').resize();
      })
      .finally(() => {
        this.setData({
          loading: false,
          loadingData: false
        });
      });
  },
  getAllService() {
    let params = {
      businessId: this.data.businessId,
      level: 3,
      btnId: this.data.btnId,
      btnType: this.data.btnType,
      classifyIds: this.data.classifyIds,
      queryType: this.data.queryType,
      beeperId: this.data.beeperId,
      businessVillageIds: this.data.businessVillageIds
    };
    $api.getAllService(params).then(res => {
      // 三级服务分类需要变为二维数组，一组为八个
      let data = res.data.data || [];
      this.setData({
        classifyList: data.length > 0 ? arrToTwoArr(res.data.data, 10) : [],
        thirdClassifyId: ''
      });
    });
  },
  // 分类改变
  classifyChange(e) {
    let id = e.currentTarget.dataset.id;
    if (!id) return;
    if (this.data.thirdClassifyId == id) id = '';
    this.setData({
      pageNo: 1,
      thirdClassifyId: id
    });
    this.getListData(true);
  },
  // 输入内容改变的时候
  inputChange(e) {
    this.setData({
      inputValue: e.detail
    });
  },
  // 根据商品关键字搜索商品
  searchShop() {
    this.setData({
      pageNo: 1
    });
    this.getListData(true);
  },
  addNum(e) {
    // 这里有三种情况，触发该函数
    // 1.事件绑定触发
    // 2.balance组件自定义事件触发
    // 3.goods-spec组件触发
    // 如果e.detail.goodsId存在那么就表示是子组件触发的这个函数
    let obj = null;
    let variantId = null;
    let index = null;
    const goodsId = e.detail.goodsId || e.currentTarget.dataset.item.goodsId;
    if (this.timeOut(goodsId)) return;
    if (e.detail.goodsId) {
      // 是goods-spec或者是balance组件调用的
      index = this.getIndexById(this.data.listData, e.detail.goodsId, 'goodsId');
      // const {specVal,relationVariantIds,relationGoodsNames} = e.detail
      const o = this.data.listData[index] || {};
      obj = { ...o, ...e.detail };
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (index != -1) {
        this.data.listData[index].nums = this.data.listData[index].nums + e.detail.nums;
        this.setData({
          listData: this.data.listData
        });
      }
    } else {
      const { item } = e.currentTarget.dataset;
      // 事件绑定触发,这里需要判断有没有关联产品而且至少有没有添加一个
      let listData = this.data.listData;
      variantId = item.variantId;
      index = this.getIndexById(this.data.listData, variantId, 'variantId');
      // 如果存在关联产品拉起选择关联产品的框框
      if (this.data.beeperId && item.relationFlag && !listData[index].nums) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
        return;
      } else {
        // 执行添加动画
        this.addAni(e.touches[0]);
        listData[index].nums++;
        this.setData({
          listData
        });
        obj = Object.assign({ ...listData[index] }, { nums: 1 });
      }
    }
    // 判断是否在活动范围之内
    const goods = this.data.listData.find(item => item.goodsId == goodsId);
    if (goods) {
      this.activeTime(goods);
    }
    // 执行父组件的addNum方法也会执行子组件的addNum方法，子组件也会执行父组件的，所以必须要用一个属性来控制，否则会陷入死循环
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').addNum(e, obj);
    }
  },
  // 添加动画
  addAni({ clientX, clientY }) {
    const { top, right } = this.data.shopCartPosition;
    this.setData({
      showDot: true,
      dotClientX: clientX - 4,
      dotClientY: clientY - 8
    });
    wx.nextTick(() => {
      const addAnimation = wx
        .createAnimation()
        .top(clientY - 20)
        .left(clientX - 50)
        .step({ duration: 100 })
        .top(top)
        .left(right - 12)
        .step({ duration: 100, timingFunction: 'ease-in' });
      this.setData({
        addAnimation: addAnimation.export()
      });
      setTimeout(() => {
        this.setData({
          showDot: false,
          addAnimation: null
        });
      }, 250);
    });
  },
  // 减少
  subNum(e) {
    let index = null;

    const goodsId = e.detail.goodsId || e.currentTarget.dataset.item.goodsId;
    if (this.timeOut(goodsId)) return;

    if (e.detail.goodsId) {
      index = this.getIndexById(this.data.listData, e.detail.goodsId, 'goodsId');
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (index != -1) {
        this.data.listData[index].nums--;
        this.setData({
          listData: this.data.listData
        });
      }
    } else {
      index = this.getIndexById(this.data.listData, e.currentTarget.dataset.item.variantId, 'variantId');
      this.data.listData[index].nums--;
      this.setData({
        listData: this.data.listData
      });
    }
    const goods = this.data.listData.find(item => item.goodsId == goodsId);
    if (goods) {
      this.activeTime(goods);
    }
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').subNum(e);
    }
  },
  // 清空数量
  clear() {
    this.data.listData.forEach(item => (item.nums = 0));
    this.setData({
      listData: this.data.listData
    });
  },
  // 判断哪些产品不在销售时间内
  judgeTimeout() {
    const { listData } = this.data;
    listData.forEach(item => {
      let res = null;
      if (!item.goodsHours || (item.goodsHours && !item.goodsHours.length)) {
        return;
      }
      res = item.goodsHours.some(item => {
        let time = new Date();
        let begin = new Date();
        let end = new Date();
        const arr = item.beginHours.split(':').map(item => Number(item));
        const arr2 = item.endHours.split(':').map(item => Number(item));
        begin.setHours(arr[0]);
        begin.setMinutes(arr[1]);
        end.setHours(arr2[0]);
        end.setMinutes(arr2[1]);
        return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
      });
      if (!res) {
        item.saleState = 0;
      }
    });
    this.setData({
      listData
    });
  },
  // 判断是否在时间段内，如果不在就要是售罄的
  timeOut(goodsId) {
    const { listData } = this.data;
    let goods = listData.find(item => item.goodsId == goodsId);
    if (!goods) {
      // 如果列表里面没有的话直接添加
      return false;
    }
    if (!goods.goodsHours || (goods.goodsHours && !goods.goodsHours.length)) return;
    const res = goods.goodsHours.some(item => {
      let time = new Date();
      let begin = new Date();
      let end = new Date();
      const arr = item.beginHours.split(':').map(item => Number(item));
      const arr2 = item.endHours.split(':').map(item => Number(item));
      begin.setHours(arr[0]);
      begin.setMinutes(arr[1]);
      end.setHours(arr2[0]);
      end.setMinutes(arr2[1]);
      return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
    });
    if (!res) {
      // 售罄之后改变状态同时清空购物车里面售罄的该数据
      goods.nums = 0;
      goods.saleState = 0;
      this.setData({
        listData
      });
      this.selectComponent('#balance').timeOut(goodsId);
      return true;
    } else {
      return false;
    }
  },
  //需要判断是不是活动时间
  activeTime(val) {
    val = Array.isArray(val) ? val : [val]; //拼接一个数组好计算
    val.forEach(item => {
      if (!item.active) return;
      let { beginDate, endDate, activePrice } = item.active;
      beginDate = getDatetime(beginDate).getTime();
      endDate = getDatetime(endDate).getTime();
      let nowDate = new Date().getTime();
      if (nowDate > beginDate && nowDate < endDate) {
        item.activeDiscount = parseFloat(((activePrice / item.price) * 10).toFixed(2)) || 0.01;
      } else {
        item.activeDiscount = '';
      }
    });
  },
  // 选择规格
  selectSpec(e) {
    if (this.timeOut(e.currentTarget.dataset.item.goodsId)) return;
    let item = e.currentTarget.dataset.item;
    let spec = this.data.spec;
    (spec.goodsId = item.goodsId), (spec.showSpec = true);
    this.setData({
      spec
    });
  },
  // 通过商品id来获取对应的数组索引，不存在就返回-1,prop是对应的字符串,默认是id
  getIndexById(arr, id, prop = 'id') {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item[prop] == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  // 去商品详情页面
  toGoodsDetail(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let beeperBtnId = e.currentTarget.dataset.beeperBtnId;
    wx.navigateTo({
      url: '/subcontract/home/pages/goodsDetail/index?goodsId=' + goodsId + '&beeperBtnId=' + beeperBtnId
    });
  },
  // 直接下单去订单结算页面
  toSubmitOrderPage(e) {
    let item = e.currentTarget.dataset.item;
    let combineId = e.currentTarget.dataset.combineid;
    if (item) {
      if (this.data.beeperId && item.relationFlag) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
      } else {
        item.nums = 1;
        app.globalData.goodsList = [item];
        // item = encodeURIComponent(JSON.stringify(e.currentTarget.dataset.item))
        wx.navigateTo({
          url: '/subcontract/home/pages/submitOrder/index'
        });
      }
    } else if (combineId) {
      wx.navigateTo({
        url: '/subcontract/home/pages/submitOrder/index?combineId=' + combineId + '&nums=' + 1
      });
    }
  },
  // 获取套餐列表
  getCombineList() {
    let params = {
      beeperId: this.data.beeperId,
      btnType: this.data.btnType,
      btnId: this.data.btnId
    };
    $api.getCombineList(params).then(res => {
      this.setData({
        combineList: res.data.data
      });
    });
  },
  // 去套餐页面
  toCombine(e) {
    let id = e.currentTarget.dataset.combineid;
    wx.navigateTo({
      url: '/subcontract/home/pages/combine/index?id=' + id
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pageNo == this.data.totalPage) return;
    // if(this.data.initNum&&this.data.listData.length>this.data.initNum)return
    this.data.pageNo++;
    this.getListData();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
